//
//  HTGoodsDetialViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/27.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTGoodsDetialViewController.h"
#import "HTGoodSourceCell.h"
#import "HTGoodSourceTypeTwoCell.h"

#import "UIImageView+WebCache.h"
#import "HTHolderVC.h"
#import "HTLineMapVC.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MapKit/MapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>


@interface HTGoodsDetialViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *mapBtn;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipsTitleLabel;

@property (weak, nonatomic) IBOutlet UILabel *assembleLabel;
@property (weak, nonatomic) IBOutlet UILabel *assembleDetialLabel;

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumLabel;
@property (weak, nonatomic) IBOutlet UIButton *detialBtn;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *callPhoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *acceptBtn;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;

@property (weak, nonatomic) IBOutlet UILabel *favorLabel;
@property (weak, nonatomic) IBOutlet UIImageView *callImageView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;

@property (nonatomic,strong) HTGoodsDetialModel *detialModel;
/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;
@end

@implementation HTGoodsDetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"货源详情";
    [self configTableView];
    [self initData];
    [self distanceValue];
    
}
- (void)initData{
    NSString *length = [HTUtils sortLengthDisplayStringWith:self.searchModel.heiht];
    NSString *type = @"不限车型";
    if (!(self.searchModel.type == nil || self.searchModel.type.length <= 0)) {
        type = self.searchModel.type;
    }
    NSString *dun = @"";
    if ([self.searchModel.utit isEqualToString:@"1"]) {
        dun =[NSString stringWithFormat:@"%@吨",self.searchModel.weight];
    }else{
        dun =[NSString stringWithFormat:@"%@方",self.searchModel.weight];
    }
    NSString *cartype = @"";
    if (!(self.searchModel.cartype == nil || self.searchModel.cartype.length <= 0)) {
        cartype = self.searchModel.cartype;
    }
    self.typeLabel.text = [NSString stringWithFormat:@"%@ %@ / %@ %@ / 运费%@元",length,type,dun,cartype,self.searchModel.pricers];
    self.startLabel.text = self.searchModel.fromadd;
    self.endLabel.text = self.searchModel.toadd;
    self.nameLabel.text = self.searchModel.drivername;
    NSString *time =  [HTUtils timeIntervalFromLastTime:self.searchModel.createtime];
    if (![time isEqualToString:@"刚刚"]) {
        time = [NSString stringWithFormat:@"%@前",time];
    }
    self.timeLabel.text = time;
    self.callPhoneLabel.text = self.searchModel.phone;
    self.phoneNumLabel.text = self.searchModel.phone;
    [HTUtils netLoadGoodsRecordWithOrderid:self.searchModel.orderid];
    if (![self.searchModel.state isEqualToString:@"0"]) {
        [self.acceptBtn setTitle:@"已被承运" forState:UIControlStateNormal];
    }
}
- (void)configTableView{
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT; self.tableView.backgroundColor = kBackgroundColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = nil;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceCell" bundle:nil] forCellReuseIdentifier:goodSourceCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceTypeTwoCell" bundle:nil] forCellReuseIdentifier:goodSourceCellTwo];
    [self configTableHeader];
    self.tableView.mj_header = self.header;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallNumber:)];
     UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallNumber:)];
    self.callPhoneLabel.userInteractionEnabled = YES;
    self.callImageView.userInteractionEnabled = YES;
    [self.callPhoneLabel addGestureRecognizer:tap];
    [self.callImageView addGestureRecognizer:tap1];
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.cornerRadius = 25;
    
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma mark --- 点击事件
- (IBAction)didClickMapBtn:(UIButton *)sender {
    
    HTLineMapVC *lineMap = [[HTLineMapVC alloc]init];
    lineMap.detialModel = self.detialModel;
    [self.navigationController pushViewController:lineMap animated:YES];
}
- (IBAction)didClickDetialBtn:(UIButton *)sender {
    
    HTHolderVC *holderVC = [[HTHolderVC alloc]init];
    holderVC.cargosid = self.detialModel.cargosid;
    [self.navigationController pushViewController:holderVC animated:YES];
    
}
- (IBAction)didClickAcceptBtn:(UIButton *)sender {
    if (![self.searchModel.state isEqualToString:@"0"]) {
        [HTShowUtil showMessage:@"该订单已被承运"];
        return;
    }
    [UIAlertController alertStyleShowInController:self title:@"温馨提示" message:@"确定承运此货源吗？" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self loadAccectGoods];
            
        }]];
    } completion:^{
        
    }];
}
- (void)didCallNumber:(id)tap{
    
    NSString *phone = self.searchModel.phone;
    NSString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    [HTUtils netLoadCallRecordWithOrderid:self.searchModel.orderid];
    
}
#pragma mark --- tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    if (model.addtype == nil || model.addtype.length <= 0) {
        return 150;
    }else{
        return 180;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    if (model.pricers== nil ||model.pricers.length <= 0) {
        HTGoodSourceTypeTwoCell *cell = (HTGoodSourceTypeTwoCell *)[tableView dequeueReusableCellWithIdentifier:goodSourceCellTwo forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        return cell;
    }else{
        HTGoodSourceCell *cell = (HTGoodSourceCell*) [tableView dequeueReusableCellWithIdentifier:goodSourceCell forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    HTGoodsDetialViewController *detial = [[HTGoodsDetialViewController alloc]init];
    detial.searchModel = model;
    [self.navigationController pushViewController:detial animated:YES];

}


#pragma mark --- 网络请求
- (void)loadNewData{
    [self netLoadMessage];
}
- (void)netLoadMessage{
    [HTHttpRequestManager requestGoodsDetialWithOrderid:self.searchModel.orderid success:^(id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
         DBLog(@"货源详情：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"数据请求失败,请下拉刷新"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
             [HTShowUtil showMessage:@"数据请求失败,请下拉刷新"];
            return;
        }
        self.detialModel = [HTGoodsDetialModel mj_objectWithKeyValues:responseObject];
        NSArray *result = responseObject[@"data"][@"data"];
        self.dataSource = [HTGoodSearchModel mj_objectArrayWithKeyValuesArray:result];
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)setDetialModel:(HTGoodsDetialModel *)detialModel{
    _detialModel = detialModel;
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:detialModel.picurl] placeholderImage:[UIImage imageNamed:@"bg_headsculpture"]options:SDWebImageRefreshCached];
    self.nameLabel.text = detialModel.drivername;
    self.phoneNumLabel.text = detialModel.phones;
    self.callPhoneLabel.text = self.searchModel.phone;
    if (self.searchModel.strattime == nil || self.searchModel.strattime.length <= 0  || self.searchModel.addtype == nil ||self.searchModel.addtype.length <= 0) {
        self.assembleLabel.text = @"";
        self.assembleDetialLabel.text = @"";
    }else{
        self.assembleLabel.text = @"装卸";
        self.assembleDetialLabel.text = [NSString stringWithFormat:@"%@ %@",self.searchModel.strattime,self.searchModel.addtype];
    }
    NSString *paytype = (detialModel.paytype == nil || detialModel.paytype.length <= 0)?@"":detialModel.paytype;
    NSString *remark = (detialModel.remark == nil || detialModel.remark.length <= 0)? @"" :detialModel.remark;
    NSString *remarkStr = (paytype.length > 0)?[NSString stringWithFormat:@"%@ %@",paytype,remark]:remark;
    if (remarkStr.length <= 0) {
        self.tipsTitleLabel.text = @"";
        self.tipsLabel.text = @"";
    }else{
        self.tipsTitleLabel.text = @"备注";
        self.tipsLabel.text = remarkStr;
    }
}

- (void)loadAccectGoods{
    [self startHud];
    [HTHttpRequestManager requestChargeOrdersWithOrderid:self.searchModel.orderid success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"接单：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"接单失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        [UIAlertController alertStyleShowInController:self title:@"温馨提示" message:@"货主同意接单后，您就可以拉货了" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
            [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        } completion:^{
            
        }];
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"接单失败"];
    }];
    
}
//计算直线距离
- (void)distanceValue{
 
   CLGeocoder *geoC = [[CLGeocoder alloc] init];
    
    [geoC geocodeAddressString:self.searchModel.fromadd completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        if(error == nil)
        {
           self.startCoordinate = pl.location.coordinate;
            [geoC geocodeAddressString:self.searchModel.toadd completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                CLPlacemark *pl = [placemarks firstObject];
                
                if(error == nil)
                {
                    self.destinationCoordinate = pl.location.coordinate;
                    MKMapPoint point1  = MKMapPointForCoordinate(self.startCoordinate);
                    MKMapPoint point2  = MKMapPointForCoordinate(self.destinationCoordinate);
                    CLLocationDistance distance = MKMetersBetweenMapPoints(point1,point2);
                    
                    self.distanceLabel.text = [NSString stringWithFormat:@"约%.1f公里",distance/1000];
                  
                }
            }];
        }
    }];
   
}
@end
